package y_ut.dbtools.exp;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import org.apache.log4j.Logger;

import au.com.bytecode.opencsv.CSVWriter;

/**
 * 
 * @author youxz
 *
 */
public class ExpCsvZipWriter implements IExpWriter {

	private Logger logger = Logger.getLogger(ExpCsvZipWriter.class);
	private String path;
	
	private ZipOutputStream zos;
	private CSVWriter writer;
	
	
	
	public ExpCsvZipWriter(String path) {
		super();
		this.path = path;
	}

	@Override
	public boolean open() {
	
		try {
			zos = new ZipOutputStream(new FileOutputStream(path));
			writer = new CSVWriter(new OutputStreamWriter(zos));
		} catch (IOException e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}

	@Override
	public void newTable(String tableName) {
		try {
			writer.flush();
			zos.putNextEntry(new ZipEntry(tableName+".csv"));
			zos.flush();
		} catch (IOException e) {
			logger.error(e);
			e.printStackTrace();
		}
		
	}

	@Override
	public void writeTableTitle(String[] data) {
		writer.writeNext(data);
	}

	@Override
	public void writeRowData(String[] data) {
		writer.writeNext(data);

	}

	@Override
	public boolean close() {
		try {
			writer.flush();
			writer.close();
		} catch (IOException e) {
			logger.error(e);
			e.printStackTrace();
		}
		return true;
	}

}
